package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/member")
public class MemberController {
    @Reference
    private MemberService memberService;
    @Autowired
    private JedisPool jedisPool;
    /**
     * //"/member/login.do",this.loginInfo
     */
    @RequestMapping("/login")
    public Result  login(HttpServletResponse response,@RequestBody Map map){
////        1.判断验证码是否正确
        String redis = (String) map.get("validateCode");
        String telephone=(String) map.get("telephone");
        String vercodeRedis = jedisPool.getResource().get( telephone+ RedisMessageConstant.SENDTYPE_LOGIN);
       if (!redis.equals(vercodeRedis) || vercodeRedis==null){
           return new Result(false, MessageConstant.VALIDATECODE_ERROR);
       }
//           2.判断是否是会员
       Member member=memberService.findMemberByPhone(telephone);
        if (member==null){
            member=new Member();
            member.setPhoneNumber(telephone);
            member.setRegTime(new Date());
            memberService.addMember(member);
        }
        //        3.写入Cookie，跟踪用户
        Cookie cookie = new Cookie("login_member_telephone",telephone);
        cookie.setPath("/");//路径
        cookie.setMaxAge(60*60*24*30);//有效期30天
        response.addCookie(cookie);
        //        4.保存会员信息在redis
        String memberJson= JSON.toJSONString(member);
        jedisPool.getResource().set(telephone,memberJson);
        return new Result(true,MessageConstant.LOGIN_SUCCESS);
    }
}
